package com.wswy.wzcx.ui.car.remind

import android.arch.lifecycle.Observer
import android.graphics.Typeface
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v4.view.PagerAdapter
import android.support.v7.app.AlertDialog
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.format.DateFormat
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.wswy.wzcx.R
import com.wswy.wzcx.model.car.Valuation
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.statistics.StatTools
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.dialog.LoadingDialog
import kotlinx.android.synthetic.main.fragment_info_valuation.*


/**
 * 估值信息
 */
class ValuationInfoFragment : CBaseFragment() {


    private lateinit var remindViewModel: RemindViewModel

    private val array = arrayOf("车况优秀","车况良好","车况一般")

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_info_valuation,container,false)
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        remindViewModel = provideViewModelFromActivity(RemindViewModel::class.java)

        tv_car_name.text = remindViewModel.userCarInfo.carExtendInfo?.carTypeData?.getInfoName()

        img_car_icon.setImageURI(remindViewModel.userCarInfo.carExtendInfo?.carTypeData?.series?.logo)


        remindViewModel.userCarInfo.carExtendInfo?.valuation?.run {
            updateInfo(this)
        }

        array.forEach {
            tabLayout.addTab(tabLayout.newTab().setText(it))
        }

        tabLayout.setupWithViewPager(vp_valuation_quote)
        vp_valuation_quote.offscreenPageLimit = array.size

        indicator.setTabLayoutAndViewPager(tabLayout, vp_valuation_quote)


        remindViewModel.getAddValuationLiveData().observe(this, Observer {

            it?.run {

                if (isOk()){
                    data?.valuation?.run {
                        updateInfo(this)
                    }


                }


            }


        })


        val dialog = LoadingDialog(context,"提交中")
        remindViewModel.getSubmitClueLiveData().observe(this, Observer {
            it?.run {

                if (inLoading()){
                    dialog.show()
                }else{
                    if (isOk()){
//                        dialog.setOnDismissListener {
//                            (activity as? RemindActivity)?.run {
//                                showInfo()
//                            }
//                        }
                        dialog.setSuccess("提交成功")

                    }else{
                        dialog.setSuccess("提交失败")
                    }
                }

            }
        })


        btn_re_valuation.setOnClickListener {
            //再次估值
            StatTools.sendClick(context, StatisticsId.addvalue_edit)

            (activity as? RemindActivity)?.run {
                showAdd()
            }

        }

        btn_sell.setOnClickListener {
            //我要卖车

            StatTools.sendClick(context, StatisticsId.addvalue_sellcar_click)

            AlertDialog.Builder(it.context).apply {

                setTitle(R.string.alert)

                setMessage(R.string.valuation_sell_hint)

                setNegativeButton(R.string.cancel){_,_ ->
                    StatTools.sendClick(context, StatisticsId.addvalue_sellcar_cancel)
                }

                setPositiveButton(R.string.ok){_,_ ->
                    //确认卖车
                    submitClue()

                    StatTools.sendClick(context, StatisticsId.addvalue_sellcar_confirm)
                }

            }.run {
                show()
            }


        }


    }


    private fun updateInfo(valuation: Valuation){




        SpannableStringBuilder().apply {

            append(valuation.registerLicenseDate)
            val color = ContextCompat.getColor(tv_car_info.context,R.color.white20)

            append(SpannableString("   |   ").apply {
                setSpan(ForegroundColorSpan(color),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
            })

            append("${valuation.drivenDistance}万公里")
            append(SpannableString("   |   ").apply {
                setSpan(ForegroundColorSpan(color),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
            })

            append(valuation.registerLicenseCity)

        }.run {
            tv_car_info.text = this
        }

        //tv_car_info.text = getString(R.string.valuation_info_hint,valuation.registerLicenseDate,valuation.drivenDistance,valuation.registerLicenseCity)

        tv_valuation_date.text = getString(R.string.valuation_hint,DateFormat.format("yyyy-MM-dd",valuation.lastValuationDate*1000))

        vp_valuation_quote.adapter = object : PagerAdapter(){
            override fun isViewFromObject(view: View, `object`: Any): Boolean = view === `object`

            override fun getCount(): Int = array.size

            override fun getPageTitle(position: Int): CharSequence? = array[position]

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                //super.destroyItem(container, position, `object`)

            }

            override fun instantiateItem(container: ViewGroup, position: Int): Any {

                val layout =  LayoutInflater.from(context).inflate(R.layout.layout_valuation_quote,container,false)


                val b2cPrice = when(position){
                    0 -> valuation.info?.c2b?.excellent?.up
                    1 -> valuation.info?.c2b?.good?.up
                    2 -> valuation.info?.c2b?.normal?.up
                    else -> null
                }


                val c2cPrice = when(position){
                    0 -> valuation.info?.c2c?.excellent?.up
                    1 -> valuation.info?.c2c?.good?.up
                    2 -> valuation.info?.c2c?.normal?.up
                    else -> null
                }

                val def = "暂无报价"

                layout.findViewById<TextView>(R.id.tv_company_price).run {
                    text = SpannableStringBuilder().apply {

                        b2cPrice?.let {
                            append(SpannableString(b2cPrice).apply {
                                setSpan(StyleSpan(Typeface.BOLD),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                            })
                            append(SpannableString(getString(R.string.wanyuan)).apply {
                                setSpan(RelativeSizeSpan(0.5f),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                            })
                        }?:kotlin.run {
                            append(SpannableString(def).apply {
                                setSpan(RelativeSizeSpan(0.75f),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)

                            })
                        }

                    }
                }

                layout.findViewById<TextView>(R.id.tv_personal_price).run {

                    text = SpannableStringBuilder().apply {

                        c2cPrice?.let {
                            append(SpannableString(c2cPrice).apply {
                                setSpan(StyleSpan(Typeface.BOLD),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                            })
                            append(SpannableString(getString(R.string.wanyuan)).apply {
                                setSpan(RelativeSizeSpan(0.5f),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                            })
                        }?:kotlin.run {
                            append(SpannableString(def).apply {
                                setSpan(RelativeSizeSpan(0.75f),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                            })
                        }

                    }
                }

                container.addView(layout)

                return layout
            }
        }
    }

    private fun submitClue(){
        remindViewModel.submitClue()
    }


}